package appcus

import (
	"counter-help/admin/server/global"
	customerRes "counter-help/admin/server/model/app/response"
	"counter-help/admin/server/model/customer"
	"errors"
)

type CusOrderFavoriteService struct{}

// FavoriteOrderByID 添加订单收藏
func (cusOrderFavoriteService *CusOrderFavoriteService) FavoriteOrderByID(userID, orderID int) error {
	// 检查是否已收藏
	var favorite customer.CusOrderFavorite
	err := global.GVA_DB.Where("user_id = ? AND order_id = ?", userID, orderID).First(&favorite).Error
	if err == nil {
		// 记录已存在，返回提示
		return errors.New("该订单已收藏")
	}

	// 创建新收藏记录
	newFavorite := customer.CusOrderFavorite{
		UserID:  &userID,
		OrderID: &orderID,
	}

	return global.GVA_DB.Create(&newFavorite).Error
}

// GetFavoriteOrdersByUserID 根据用户 ID 获取收藏的订单列表
func (cusOrderFavoriteService *CusOrderFavoriteService) GetFavoriteOrdersByUserID(userID int) ([]customerRes.CusOrderSimpleResponse, error) {
	var favorites []customer.CusOrderFavorite
	err := global.GVA_DB.Where("user_id = ?", userID).Find(&favorites).Error
	if err != nil {
		return nil, err
	}

	var orderIDs []int
	for _, favorite := range favorites {
		orderIDs = append(orderIDs, *favorite.OrderID)
	}

	// 查询所有收藏的订单详细信息
	var orders []customer.CusOrder
	err = global.GVA_DB.Where("id IN ?", orderIDs).Find(&orders).Error
	if err != nil {
		return nil, err
	}

	// 转换为响应格式
	var orderResponses []customerRes.CusOrderSimpleResponse
	for _, order := range orders {
		orderResponses = append(orderResponses, convertCusOrderToSimpleResponse(order))
	}

	return orderResponses, nil
}

// UnfavoriteOrderByID 取消订单收藏
func (cusOrderFavoriteService *CusOrderFavoriteService) UnfavoriteOrderByID(userID, orderID int) error {
	// 删除指定的收藏记录
	return global.GVA_DB.Where("user_id = ? AND order_id = ?", userID, orderID).Delete(&customer.CusOrderFavorite{}).Error
}
